package com.sicpa.common.ftp;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.concurrent.ArrayBlockingQueue;

/**
 * FtpFactory
 *
 * @author lwf
 */
@Component
public class FtpFactory {

    private final ArrayBlockingQueue<FtpConnection> arrayBlockingQueue = new ArrayBlockingQueue<>(10);

    private static Logger log = LoggerFactory.getLogger(FtpFactory.class);

    public FtpFactory() {
//        for (int i = 0; i < 10; i++) {
//            arrayBlockingQueue.offer(new FtpConnection());
//        }
    }

    /**
     * 获取连接
     *
     * @return
     */
    public FtpConnection getFtp() throws InterruptedException, IOException {
//        FtpConnection poll = null;
//        poll = arrayBlockingQueue.take();
//        if(!poll.isConnected()){
//            poll.intiConnect();
//        }
        return new FtpConnection();
    }

    /**
     * 释放连接
     *
     * @param ftp
     * @return
     */
    public boolean relase(FtpConnection ftp) {
        return arrayBlockingQueue.offer(ftp);
    }

    /**
     * 删除连接
     *
     * @param ftp
     */
    public void remove(FtpConnection ftp) {
        arrayBlockingQueue.remove(ftp);

    }

    /**
     * 关闭连接
     */
    public void close() {
        for (FtpConnection connection : arrayBlockingQueue) {
            try {
                connection.disconnect();
            } catch (IOException e) {
                log.error(e.getMessage(), e);
            }
        }
    }

}
